'use client'

import { useState, useCallback, useEffect } from 'react'

export function useAppointmentData({ initialCampuses, getCourts, getAllUsers, getAppointments, getCoursePackages }) {
  const [branchCampus, setBranchCampus] = useState(initialCampuses[0])
  const [courts, setCourts] = useState([])
  const [coaches, setCoaches] = useState([])// 校区内的教练
  const [clients, setClients] = useState([])
  const [appointments, setAppointments] = useState([])
  const [selectedCourt, setSelectedCourt] = useState(null)
  const [coursePackages, setCoursePackages] = useState([])


  const [clientAndCoursePackages, setClientAndCoursePackages] = useState([])

  const fetchCoursePackages = useCallback(async () => {
    if (!branchCampus) return
    const coursePackages = await getCoursePackages({ branch_campus_id: branchCampus?.id })
    setCoursePackages(coursePackages)
  }, [branchCampus, getCoursePackages])

  // 获取场地列表
  const fetchCourts = useCallback(async () => {
    if (!branchCampus) return
    try {
      const courts = await getCourts({ branch_campus_id: branchCampus?.id })
      setCourts(courts)
      setSelectedCourt(courts[0]?.id) // 重置选中的场地
    } catch (error) {
      console.error('获取场地失败:', error)
    }
  }, [branchCampus, getCourts])

  // 获取教练列表
  const fetchCoaches = useCallback(async () => {
    if (!branchCampus) return
    try {
      const coaches = await getAllUsers({ role: 'coach', branch_campus_id: branchCampus?.id })
      setCoaches(coaches)
    } catch (error) {
      console.error('获取教练失败:', error)
    }
  }, [branchCampus, getAllUsers])

  // 获取学员列表
  const fetchClients = useCallback(async () => {
    if (!branchCampus) return
    try {
      const clients = await getAllUsers({ role: 'client', branch_campus_id: branchCampus?.id })
      setClients(clients)
    } catch (error) {
      console.error('获取学员失败:', error)
    }
  }, [branchCampus, getAllUsers])

  // 获取已预约列表
  const fetchAppointments = useCallback(async () => {
    if (!branchCampus) return
    try {
      const appointments = await getAppointments({
        branch_campus_id: branchCampus?.id,
        status: "pending"
      })
      setAppointments(appointments)
      console.log('fetchAppointments appointments', appointments)
    } catch (error) {
      console.error('获取预约失败:', error)
    }
  }, [branchCampus, getAppointments])

  // 当校区改变时，重新获取场地和用户数据
  useEffect(() => {
    if (branchCampus) {
      fetchCourts()
      fetchCoaches()
      fetchClients()
      fetchCoursePackages()
    }
  }, [branchCampus, fetchCourts, fetchCoaches, fetchClients, fetchCoursePackages])

  useEffect(() => {
    // 确保 clients 和 coursePackages 都存在且有数据
    if (!clients?.length || !coursePackages?.length) return;

    // 组装级联数据
    const cascadingData = clients.map(client => {
      // 找到该学员的所有课程包
      const clientPackages = coursePackages.filter(pkg =>
        pkg.client_id === client.id && pkg.left_count > 0 // 只显示还有剩余课时的课程包
      );

      // 如果该学员有课程包，则构建子级选项
      return {
        label: client.name, // 学员姓名作为一级标签
        value: client.id,   // 学员ID作为一级值
        children: clientPackages.map(pkg => ({
          label: `${pkg.course_type} (剩余${pkg.left_count}课时)`, // 课程包名称和剩余课时作为二级标签
          value: pkg.id,    // 课程包ID作为二级值
        }))
      };
    }).filter(item => item.children.length > 0); // 只保留有可用课程包的学员

    setClientAndCoursePackages(cascadingData);
  }, [coursePackages, clients]);

  // 当场地改变时，重新获取预约数据
  useEffect(() => {
    fetchAppointments()
  }, [fetchAppointments])

  return {
    branchCampus,
    setBranchCampus,
    courts,
    coaches,
    appointments,
    fetchAppointments,
    selectedCourt,
    setSelectedCourt,
    clientAndCoursePackages,
    refreshData: {
      refreshCourts: fetchCourts,
      refreshCoaches: fetchCoaches,
      refreshClients: fetchClients,
      refreshAppointments: fetchAppointments
    }
  }
}